package main

import (
	"os"
	"os/signal"
	"smart-flow/container/config"
	"smart-flow/container/http"
	"smart-flow/container/logger"
	"smart-flow/container/tcp"
	"smart-flow/container/udp"
	"syscall"
	"time"

	"go.uber.org/zap"
)

var (
	quit chan os.Signal
)

func init() {
	config.LoadConfig("./resource")
	logger.InitLogger(config.AppConfig.Log.LogPath, config.AppConfig.Container.Mode)
	config.InitRuntime()
	quit = make(chan os.Signal, 1)
}

func main() {
	logger.Logger.Info("[容器] --- 启动容器服务 ---")
	logger.Logger.Info("[容器] 服务配置", zap.Any("config", config.AppConfig))
	tcpManager := new(tcp.ServerManager)
	if !tcpManager.Start() {
		logger.Logger.Error("[容器] tcp 服务集群启动异常")
		return
	}
	logger.Logger.Info("[容器] tcp 服务集群已启动")
	udpManager := new(udp.ServerManager)
	if !udpManager.Start() {
		logger.Logger.Error("[容器] udp 服务集群启动异常")
		return
	}
	logger.Logger.Info("[容器] udp 服务集群已启动")
	httpManager := new(http.ServerManager)
	if !httpManager.Start() {
		logger.Logger.Error("[容器] http 服务集群启动异常")
		return
	}
	logger.Logger.Info("[容器] http 服务集群已启动")
	// go service.Exchange()
	signalHandler(tcpManager, udpManager, httpManager)
}

func signalHandler(tcpManager *tcp.ServerManager, udpManager *udp.ServerManager, httpManager *http.ServerManager) {
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	logger.Logger.Info("[容器] 关闭中...")
	tcpManager.Stop()
	logger.Logger.Info("[容器] tcp 服务集群已关闭")
	time.Sleep(time.Second)
	udpManager.Stop()
	logger.Logger.Info("[容器] udp 服务集群已关闭")
	time.Sleep(time.Second)
	httpManager.Stop()
	logger.Logger.Info("[容器] http 服务集群已关闭")
	time.Sleep(time.Second)
	logger.Logger.Info("[容器] 已关闭")
}
